/**
 * 
 */
package edu.unr.cater.npap.server.security;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author Hao
 * 
 */
public class UserAuthenticationProvider implements AuthenticationProvider {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * authenticate(org.springframework.security.core.Authentication)
	 */
	private static Map<String, String> users = new HashMap<String, String>();

	static {
		users.put("hao", "hao");
		users.put("tian", "tian");
	}

	@Override
	public Authentication authenticate(Authentication arg0)
			throws AuthenticationException {
		// TODO Auto-generated method stub

		String username = (String) arg0.getPrincipal();
		String password = (String) arg0.getCredentials();

		if (users.get(username) == null)
			throw new UsernameNotFoundException("User not found");
		String storedPass = users.get(username);
		if (!storedPass.equals(password))
			throw new BadCredentialsException("Invalid password");
		Authentication customAuthentication = new CustomUserAuthentication(
				"ROLE_USER", arg0);
		customAuthentication.setAuthenticated(true);
		return customAuthentication;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.authentication.AuthenticationProvider#supports
	 * (java.lang.Class)
	 */
	@Override
	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(arg0);

	}

}
